<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>案例_头像上传</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <style>
        .thumb-box {
            text-align: center;
            margin-top: 50px;
        }

        .thumb {
            width: 250px;
            height: 250px;
            object-fit: cover;
            border-radius: 50%;
            border: 5px solid black !important;
        }
    </style>
</head>

<body>
    <div class="thumb-box">
        <!-- 头像 -->
        <img id="img" class="img-thumbnail thumb" src="./lib/images/cover.jpg">
        <div class="mt-2">
            <!-- change事件 -->
            <input style="display: none;" type="file" id="iptFile" accept="image/*">
            <button id="btn">选择头像</button>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/axios@0.27.2/dist/axios.min.js"></script>
    <script>
        document.querySelector('#btn').addEventListener('click', () => {
            // alert(1)
            // 模拟：点击了文件域
            document.querySelector('#iptFile').click()
        })
        // input type="file" 有一个change事件，事件对象中保存用户选中的文件
        document.querySelector('#iptFile').addEventListener('change', (e) => {
            console.log(e.target.files)
            if(e.target.files.length === 0) {
                return
            }
            // 拿到我们要上传的文件
            const file = e.target.files[0]
            console.log('开始做上传文件....', file)

            const fd = new FormData()
            fd.append('avatar', file)

            axios({
                url: 'http://ajax-api.itheima.net/api/file',
                method: 'POST',
                data: fd
                // data: {
                //     avatar: file
                // }
            }).then(res => {
                // 图片被上传到了这里
                // 显示出来
                console.log(res.data.data.url)
                document.querySelector('#img').src = res.data.data.url
            })
        })
    </script>
</body>

</html>